#include "loggermanager.h"
#include <QDateTime>
#include <QDir>
#include <iostream>

LoggerManager& LoggerManager::getInstance()
{
    static LoggerManager instance;
    return instance;
}

void LoggerManager::init()
{
    QString logDirPath = "logs";
    QString dbPath = "logs/system_logs.db";

    try
    {
        // 创建日志目录（如果不存在）
        QDir dir(logDirPath);
        if (!dir.exists())
        {
            dir.mkpath(".");
        }

        // 动态生成日志文件名
        QString timestamp = QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss");
        QString logFilePath = logDirPath + "/" + timestamp + ".log";

        // 初始化 spdlog
        auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
        auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(logFilePath.toStdString(), true);

        std::vector<spdlog::sink_ptr> sinks{console_sink, file_sink};
        logger = std::make_shared<spdlog::logger>("multi_sink", sinks.begin(), sinks.end());

        logger->set_level(spdlog::level::info);
        logger->set_pattern("[%Y-%m-%d %H:%M:%S] [%l] %v");

        spdlog::register_logger(logger);

        // 初始化 SQLite 数据库
        db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName(dbPath);

        if (!db.open())
        {
            logger->error("Failed to open database: {}", db.lastError().text().toStdString());
        }
        else
        {
            QSqlQuery query;
            query.exec("CREATE TABLE IF NOT EXISTS system_logs ("
                       "log_id INTEGER PRIMARY KEY AUTOINCREMENT, "
                       "timestamp DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, "
                       "type TEXT NOT NULL, "
                       "content TEXT NOT NULL, "
                       "CHECK (type IN ('error', 'operation', 'info', 'warning')))");
        }
    }
    catch (const spdlog::spdlog_ex& ex)
    {
        std::cerr << "Log initialization failed: " << ex.what() << std::endl;
    }
}

std::shared_ptr<spdlog::logger> LoggerManager::getLogger()
{
    return logger;
}

void LoggerManager::logInfo(const QString& content)
{
    logger->info(content.toStdString());
    logToDatabase("info", content);
}

void LoggerManager::logWarning(const QString& content)
{
    logger->warn(content.toStdString());
    logToDatabase("warning", content);
}

void LoggerManager::logError(const QString& content)
{
    logger->error(content.toStdString());
    logToDatabase("error", content);
}

void LoggerManager::logOperation(const QString& content)
{
    logger->info(content.toStdString());  // 使用 info 级别记录 operation 日志
    logToDatabase("operation", content);
}

void LoggerManager::logToDatabase(const QString& type, const QString& content)
{
    if (db.isOpen())
    {
        QSqlQuery query;
        query.prepare("INSERT INTO system_logs (type, content) VALUES (:type, :content)");
        query.bindValue(":type", type);
        query.bindValue(":content", content);

        if (!query.exec())
        {
            logger->error("Failed to insert log into database: {}", query.lastError().text().toStdString());
        }
    }
    else
    {
        logger->error("Database is not open");
    }
}
